package webSocket.handler;

import java.text.SimpleDateFormat;
import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;

import com.alibaba.druid.support.json.JSONParser;
import com.alibaba.fastjson.JSON;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelId;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.util.AttributeKey;
import util.constant.Constant;
import util.netty.WebsocektResponse;
import util.netty.WebsocketRequest;
import util.spring.SpringUtils;
import webSocket.channel.QQ_ChannelGroup;

public class WebSocketMsgHandler extends SimpleChannelInboundHandler<TextWebSocketFrame>{

	@Autowired
	private QQ_ChannelGroup group = SpringUtils.getBean(QQ_ChannelGroup.class);
	
	private SimpleDateFormat msgFormet = new SimpleDateFormat("yyyy-MM-dd HH:mm");
	
	
	@Override
	protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame msg) throws Exception {
		//目前只打算做单对单,所以要解析出谁对谁说话, 然后发送
		String json = msg.text();
		WebsocketRequest request = JSON.parseObject(json, WebsocketRequest.class);
		System.out.println(json);
		
		if(request.getCode().equals(Constant.REQUEST.FIND_ALL_USER)) {
			findAllUser(ctx.channel());
		}
		else if(request.getCode().equals(Constant.REQUEST.SENT_TO)) {
			sendMsg(request, ctx.channel());
		}
		

		
	}
	
	
	/**
	 * 查询所有用户, 讲其他用户信息发送到前端
	 * @param channel 当前channel
	 */
	private void findAllUser(Channel channel) {
		for(ChannelId id : group.getChannelIds()) {
			
			if(!channel.id().equals(id)) {
				Channel temp = group.getChannelGroup().find(id);
				String onlineName = temp.attr(AttributeKey.valueOf("name")).get().toString();
				String onlineTime = temp.attr(AttributeKey.valueOf("onlineTime")).get().toString();
				
				WebsocektResponse response = new WebsocektResponse(Constant.RESPONSE.ON_LINE, onlineName);
				response.setHour(onlineTime);
				
				channel.write(new TextWebSocketFrame(JSON.toJSONString(response)).retain());
			}
		}
		channel.flush();
	}
	
	/**
	 * 发送信息到aimAlias
	 * @param request
	 */
	public void sendMsg(WebsocketRequest request, Channel currChannel) {
		String text = request.getContext();
		String aimAlias = request.getAimAlias();
		String alias = currChannel.attr(AttributeKey.valueOf("name")).get().toString();
		
		for(ChannelId id : group.getChannelIds()) {
			Channel channel = group.getChannelGroup().find(id);
			String userAlias = channel.attr(AttributeKey.valueOf("name")).get().toString();
			if(userAlias.equals(aimAlias)) {
				WebsocektResponse response = new WebsocektResponse(Constant.RESPONSE.MSG, alias, text, msgFormet.format(new Date()));
				channel.writeAndFlush(new TextWebSocketFrame(JSON.toJSONString(response)).retain());
			}
		}
	}
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	

}
